package pers.sloera.interview;

/**
 * 华为一面
 * 现有一个整形数组，例如int[] datas = {1,4,-3,0,6.....},请实现一个方法来计算这个整形数组中加和等于K的最长的连续序列的长度？
 * <p>
 * class pers.sloera.tulin
 * 刘汪洋 2022-03-18
 */
public class findK {
    public static void main(String[] args) {
        int[] datas = {1, 4, -3, 2, -2, 0, 6, -4,};
        int length = findLengthOfK(datas, 3);
        System.out.println(length);
    }

    /**
     * 现有一个整形数组，例如int[] datas = {1,4,-3,0,6.....},请实现一个方法来计算这个整形数组中加和等于K的最长的连续序列的长度？
     * <p>
     * class pers.sloera.tulin
     * 刘汪洋 2022-03-18
     */
    private static int findLengthOfK(int[] datas, int dest) {
        int maxLength = 0;
        for (int i = 0; i < datas.length; i++) {
            for (int leftIndex = i; leftIndex >= 0; leftIndex--) {
                for (int rightIndex = i; rightIndex < datas.length; rightIndex++) {
                    if (dest == sum(datas, leftIndex, rightIndex)) {
                        maxLength = Math.max(maxLength, rightIndex - leftIndex + 1);
                    }
                }
            }
        }
        return maxLength;
    }

    private static int sum(int[] datas, int leftIndex, int rightIndex) {
        int sum = 0;
        for (int j = leftIndex; j <= rightIndex; j++) {
            sum = sum + datas[j];
        }
        return sum;
    }
}
